package cn.omisheep.commons.util.web;

import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author zhouxinchen[1269670415@qq.com]
 * @since 1.0.4
 */
public class URLParser {

    private URLParser() {
        throw new UnsupportedOperationException();
    }

    public static URLInfo parse(String url) {
        URLInfo urlInfo = new URLInfo();
        int     i1      = url.indexOf(":");
        int     i2      = url.indexOf("/", 9);
        if (i2 == -1) {
            i2 = url.length();
            urlInfo.setPath(url.substring(0, i2));
        } else {
            int i3 = url.indexOf("?");
            if (i3 != -1) {
                urlInfo.setUri(url.substring(i2, i3)).setParam(url.substring(i3 + 1)).setPath(url.substring(0, i3));
            } else {
                urlInfo.setUri(url.substring(i2)).setPath(url);
            }
        }
        urlInfo.setProtocol(url.substring(0, i1)).setDomain(url.substring(i1 + 3, i2));
        return urlInfo;
    }

    public static class URLInfo {
        private String              protocol;
        private String              domain;
        private String              uri;
        private String              path;
        private Map<String, String> param = new HashMap<>();

        public URLInfo() {
        }

        @Override
        public String toString() {
            return new StringJoiner(", ", URLInfo.class.getSimpleName() + "[", "]")
                    .add("protocol='" + protocol + "'")
                    .add("domain='" + domain + "'")
                    .add("uri='" + uri + "'")
                    .add("path='" + path + "'")
                    .add("param=" + param)
                    .toString();
        }

        public URLInfo setParam(String param) {
            this.param.putAll(ConvertUtil.stringToMap(param));
            return this;
        }

        public String getProtocol() {
            return protocol;
        }

        public URLInfo setProtocol(String protocol) {
            this.protocol = protocol;
            return this;
        }

        public String getDomain() {
            return domain;
        }

        public URLInfo setDomain(String domain) {
            this.domain = domain;
            return this;
        }

        public String getUri() {
            return uri;
        }

        public URLInfo setUri(String uri) {
            this.uri = uri;
            return this;
        }

        public String getPath() {
            return path;
        }

        public URLInfo setPath(String path) {
            this.path = path;
            return this;
        }

        public Map<String, String> getParam() {
            return param;
        }

        public URLInfo setParam(Map<String, String> param) {
            this.param = param;
            return this;
        }
    }

}
